package com.doule.farmerassistant.task;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.doule.farmerassistant.R;
import com.doule.farmerassistant.TasksSqlHelper;
import com.doule.farmerassistant.DeathConfig;
//import com.doule.farmerassistant.plan.CreatePlanActivity;
//import com.doule.farmerassistant.plan.PlanFragment;
import com.doule.farmerassistant.MyService;

import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
//import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;

/**
 * Task fragment class.
 * 
 * @author riguang
 * 
 */
public class TaskFragment extends Fragment implements MyService.NotifyListener {
    /**
     * TaskFragment class tag.
     */
    private static final String TAG = "TaskListActivity";

    /**
     * TaskFragment instance.
     */
    private static TaskFragment mInstance;

    /**
     * LoadTask class.
     */
    private LoadTask mLoadTask;

    /**
     * Authentication token.
     */
    private String mToken;

    /**
     * 
     */
    private LinearLayout mProgress;

    /**
     * Task ListView.
     */
    private ListView mTaskListView;

    /**
     * TaskDetail table.
     */
    private ArrayList<TaskDetail> mTaskList;

    /**
     * TaskAdapter.
     */
    private TaskAdapter mTaskAdapter;

    /**
     * Get mTaskList.
     * 
     * @return mTaskList
     */
    public ArrayList<TaskDetail> getTaskList() {
        return mTaskList;
    }

    /**
     * get singleton instance.
     * @return instance
     */
    public static TaskFragment getInstance() {
        return mInstance;
    }
    
    /**
     * get task by id.
     * @param id task id
     * @return task
     */
    public TaskDetail getTask(final String id) {
        for (TaskDetail t: mTaskList) {
            if (t.getId().equals(id)) {
                return t;
            }
        }
        
        return null;
    }
    
    /**
     * Get mTaskAdapter.
     * 
     * @return mTaskAdapter
     */
    public TaskAdapter getTaskAdapter() {
        return mTaskAdapter;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = LayoutInflater.from(getActivity()).inflate(
                R.layout.fragment_task, null);

        mInstance = this;
        mTaskListView = (ListView) v.findViewById(R.id.lv_task);
        mTaskList = new ArrayList<TaskDetail>();
        mTaskAdapter = new TaskAdapter(this.getActivity(), mTaskList);
        mTaskListView.setAdapter(mTaskAdapter);
        mTaskListView.setOnItemClickListener(onItemClickListener);

        mToken = this.getActivity().getIntent().getStringExtra("tk");
        // mAccount = this.getActivity().getIntent().getStringExtra("account");
        mProgress = (LinearLayout) v.findViewById(R.id.progress_view);
        
        mTaskListView.setVisibility(View.GONE);
        mProgress.setVisibility(View.VISIBLE);
        mLoadTask = new LoadTask(mToken);
        mLoadTask.execute((Void) null);
        // text = (TextView) v.findViewById(R.id.text);
        // if (getArguments() != null) {
        // //
        // try {
        // String value = getArguments().getString("key");
        // text.setText("Current Tab is: " + value);
        // } catch (Exception e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        // }
        
        MyService.getInstance().setNotifyListener("/taskstatus", this);
        
        return v;
    }

    @Override
    public void onDestroy() {
        MyService.getInstance().removeNotifyListener("/taskstatus", this);
        super.onDestroy();
        if (mProgress != null) {
            mProgress = null;
        }
    }

    /**
     * Start TaskControlActivity.
     * 
     * @param taskDetail
     *            TaskDetail
     */
    private void startTaskControlActivity(TaskDetail taskDetail) {
        Intent intent = new Intent();
        intent.setClass(mInstance.getActivity(), TaskControlActivity.class);
        intent.putExtra("id", taskDetail.getId());
        intent.putExtra("tk", mToken);
        startActivity(intent);
    }

    /**
     * On item click listener.
     */
    private OnItemClickListener onItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                long arg3) {
            // TODO Auto-generated method stub
            if (position < 0 || position > (mTaskList.size() - 1)) {
                return;
            }

            TaskDetail taskDetail = mTaskList.get(position);
            if (taskDetail == null) {
                return;
            }

            startTaskControlActivity(taskDetail);
        }

    };

    /**
     * Load task.
     */
    final class LoadTask extends AsyncTask<Void, Void, Boolean> {
        /**
         * Authentication token.
         */
        private String mToken;

        /**
         * 
         */
        private String mError;

        /**
         * Constructor.
         * 
         * @param token
         *            Authentication token
         */
        private LoadTask(final String token) {
            mToken = token;
        }

        /**
         * parser jsonString.
         * 
         * @param jsonString
         *            jsonString
         */
        private void parseJson(final String jsonString) {
            Log.e("LocadTask", "jsonString: " + jsonString);
            try {
                JSONArray jsonArray = new JSONArray(jsonString);
                if (jsonArray.length() < 0) {
                    return;
                }
                TasksSqlHelper.dropTasks();
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject obj = jsonArray.getJSONObject(i);
                    String type = "", id = "", name = "", perbatch = "", duration = "";
                    if (obj.has("type")) {
                        type = obj.getString("type");
                    }

                    if (obj.has("id")) {
                        id = obj.getString("id");
                    }

                    if (obj.has("name")) {
                        name = obj.getString("name");
                    }

                    if (obj.has("perbatch")) {
                        perbatch = obj.getString("perbatch");
                    }

                    if (obj.has("duration")) {
                        duration = obj.getString("duration");
                    }

                    TaskDetail.TaskStatus status = TaskDetail.TaskStatus.Stop;
                    if (obj.has("status")) {
                        String s = obj.getString("status");
                        if (s.equals("run")) {
                        status = TaskDetail.TaskStatus.Running;
                        }
                    }
                    
                    TaskDetail detail = new TaskDetail(type, id, name,
                        perbatch, duration, status);
                    mTaskList.add(detail);
                    //TasksSqlHelper.saveTasks(id, type, name, perbatch,
                            //duration);
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        /**
         * Load task.
         * 
         * @return true if load task success.
         */
        private boolean loadTask() {
            String serverUrl = DeathConfig.getServerUrl();
            if (serverUrl == null || serverUrl.equals("")) {
                mError = "please setting server url !";
                return false;
            }

            Log.e("UserLoginTask", "token: " + mToken);
            HttpPost request = new HttpPost(serverUrl + "/loadTasks");
            request.setHeader("content-type", "application/json");
            request.setHeader("tk", mToken);

            AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
            try {
                HttpResponse resp = client.execute(request);
                Header head = resp.getFirstHeader("error");
                if (null != head) {
                    mError = head.getValue();
                    Log.e("UserLoginTask", "login error: " + mError);
                    return false;
                }

                HttpEntity entity = resp.getEntity();
                String strResult = EntityUtils.toString(entity, "UTF-8");
                parseJson(strResult);
                // Log.e("LoadTask", "strResult: " + mTaskJSONStr);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                client.close();
            }
            return false;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            if (loadTask()) {
                return true;
            }

            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mLoadTask = null;
            // showProgress(false);

            if (success) {
                mTaskAdapter.notifyDataSetChanged();
                mProgress.setVisibility(View.GONE);
                mTaskListView.setVisibility(View.VISIBLE);
                // finish();
            } else {
                Log.e(TAG, "load task error: " + mError);
            }
        }

        @Override
        protected void onCancelled() {
            mLoadTask = null;
            // showProgress(false);
        }
    }

    @Override
    public void onJSONNotify(JSONObject jobject) {
        try {
            String taskId = jobject.getString("taskid");
            TaskDetail td = getTask(taskId);
            if (td == null) {
                return;
            }
            
            String status = jobject.getString("status");
            if (status.equals("run")) {
                td.setStatus(TaskDetail.TaskStatus.Running);
            } else {
                td.setStatus(TaskDetail.TaskStatus.Stop);
            }
            
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
